<template>
    <div class="register-container">
  <el-card class="register">
    <h2>注册</h2>
    
    <el-form 
      :model="registerForm" 
      ref="registerFormRef" 
      :rules="rules" 
      label-width="80px"
      @submit.prevent="handleRegister"
    >
      <!-- 头像上传区域 -->
      <el-form-item label="头像" class="avatar-upload">
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :http-request="handleAvatarUpload"
          :before-upload="beforeAvatarUpload"
          :on-error="handleUploadError"
          :on-success="handleUploadSuccess"
          :disabled="loading"
        >
          <!-- 头像容器 - 确保图片正确适应 -->
          <div class="avatar-container">
            <img 
              v-if="registerForm.avatarUrl" 
              :src="registerForm.avatarUrl" 
              class="avatar-image" 
              @load="handleImageLoad"
              :alt="`${registerForm.nickname || '用户'}的头像`"
            />
            <el-icon v-else class="avatar-uploader-icon"><EpPlus /></el-icon>
          </div>
        </el-upload>
        <div class="upload-tip">支持JPG、PNG格式,不超过2MB</div>
        <el-alert 
          v-if="uploadError" 
          :title="uploadError" 
          type="error" 
          show-icon 
          style="margin-top: 10px; padding: 5px 10px;"
          :closable="true"
          @close="uploadError = ''"
        />
      </el-form-item>

      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" autocomplete="username" />
        <div class="format-tip">用户名长度为1-20个字符，可包含字母、数字</div>
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerForm.password" type="password" autocomplete="new-password" show-password />
        <div class="format-tip">密码长度至少为8位，包含字母和数字</div>
      </el-form-item>
      
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="registerForm.confirmPassword" type="password" show-password />
        <div class="format-tip">请输入与上面相同的密码</div>
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email" type="email" />
        <div class="format-tip">请输入有效的邮箱地址（例如：example@domain.com）</div>
      </el-form-item>
      
      <el-form-item label="电话" prop="phone">
        <el-input v-model="registerForm.phone" />
        <div class="format-hint">请输入11位有效的手机号码（例如：13800138000）</div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" native-type="submit" :loading="loading">注册</el-button>
      </el-form-item>
      
      <el-form-item v-if="errorMsg">
        <el-alert :title="errorMsg" type="error" show-icon />
      </el-form-item>
    </el-form>
    
    <div class="register-link">
      已有账号？
      <a @click.prevent="goLogin" href="#">去登录</a>
    </div>
  </el-card>
</div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import authApi from '../../api/auth' 

const router = useRouter()
const authStore = useAuthStore()

const registerFormRef = ref(null)
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
  avatarUrl: '',      // 头像URL
  avatarFile: null    // 头像文件对象（用于临时预览）
})

// 状态管理
const loading = ref(false)        // 整体加载状态
const errorMsg = ref('')          // 注册错误信息
const uploadError = ref('')       // 头像上传错误信息
const isUploading = ref(false)    // 上传中状态

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 20, message: '用户名长度在1-20个字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8,  message: '密码长度至少为8位，包含字母和数字', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d).+$/, message: '密码至少包含一个字母和一个数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式（例如：example@domain.com）', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入11位有效的手机号码', trigger: 'blur' }
  ]
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  uploadError.value = ''  // 重置上传错误
  
  // 验证文件类型
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    uploadError.value = '请上传JPG或PNG格式的图片'
    return false
  }
  
  // 验证文件大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    uploadError.value = '图片大小不能超过2MB'
    return false
  }
  
  // 生成临时预览URL（不经过服务器）
  const reader = new FileReader()
  reader.onload = (e) => {
    registerForm.avatarUrl = e.target.result  // 临时显示本地图片
  }
  reader.readAsDataURL(file)
  
  registerForm.avatarFile = file  // 保存文件对象，稍后随注册一起提交
  isUploading.value = true
  
  return true
}

// 处理头像上传（这里不实际上传，而是在注册时一起提交）
const handleAvatarUpload = async (options) => {
  try {
    // 模拟上传成功，实际项目中可以在这里先上传到临时存储
    // 或者直接在注册时一起提交头像文件
    setTimeout(() => {
      options.onSuccess({ status: 'success' })
      isUploading.value = false
    }, 500)
  } catch (error) {
    options.onError(error)
    isUploading.value = false
  }
}

// 上传成功处理
const handleUploadSuccess = () => {
  ElMessage.success('头像预览成功')
}

// 上传错误处理
const handleUploadError = (error) => {
  uploadError.value = '头像处理失败: ' + (error.message || '请重试')
  console.error('头像处理错误:', error)
}

// 图片加载完成后调整显示方式
const handleImageLoad = (e) => {
  const img = e.target;
  const container = img.parentElement;
  
  // 根据图片和容器尺寸自动调整显示方式
  if (img.naturalWidth > container.clientWidth || img.naturalHeight > container.clientHeight) {
    // 图片大于容器，裁剪显示
    img.style.objectFit = 'cover';
  } else {
    // 图片小于容器，完整显示
    img.style.objectFit = 'contain';
  }
};

// 处理注册提交
const handleRegister = async () => {
  loading.value = true
  errorMsg.value = ''
  uploadError.value = ''
  
  try {
    // 验证表单
    await registerFormRef.value.validate()
    
    // 调用注册接口
    const response = await authApi.register({
      username: registerForm.username,
      password: registerForm.password,
      email: registerForm.email,
      phone: registerForm.phone
    })    
    if (response.code === 200) {
      ElMessage.success(response.msg || '注册成功，请登录')
      router.push('/')
    } else {
      // 处理用户名重复等错误
      if (response.msg.includes('用户名')) {
        errorMsg.value = response.msg
      } else {
        errorMsg.value = response.msg || '注册失败，请重试'
      }
    }
  } catch (error) {
    console.error('注册失败:', error)
    // 将可能的英文错误信息转为中文
    if (error.name !== 'ValidationError') {
      let errorText = error.message || '注册失败，请重试'
      // 常见错误信息翻译
      if (errorText.includes('Network Error')) errorText = '网络错误，请检查网络连接'
      if (errorText.includes('timeout')) errorText = '请求超时，请稍后重试'
      if (errorText.includes('404')) errorText = '请求地址不存在'
      if (errorText.includes('500')) errorText = '服务器错误，请稍后重试'
      
      errorMsg.value = errorText
    }
  } finally {
    loading.value = false
  }
}

// 跳转到登录页
const goLogin = () => {
  router.push('/')
}
</script>

<style scoped>
.register-container {
  background: #304156;
  background-size: cover;
  background-position: center;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.register {
  width: 450px;  
  max-width: 90vw;  
  margin: 80px auto; 
  padding: 25px; 
  background-color: rgba(255, 255, 255, 0.871);
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.08); 
}
.register-link a {
  color: #409EFF;
  cursor: pointer;
  margin-left: 4px;
  text-decoration: underline;
}

/* 头像上传样式 - 优化核心部分 */
.avatar-upload {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

/* 头像容器 - 固定尺寸圆形 */
.avatar-container {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  border: 1px dashed #ccc;
  background-color: #f9f9f9;
  transition: all 0.3s ease;
}

/* 头像图片 - 自适应容器 */
.avatar-image {
  width: 100%;
  height: 100%;
  /* 核心属性：保持比例填充容器 */
  object-fit: cover;
  transition: all 0.3s ease;
}

/* 上传图标样式 */
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 100px;
  position: absolute;
  top: 0;
  left: 0;
}

.upload-tip {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
  width: calc(100% - 100px - 16px);
}

/* 格式提示样式 */
.format-tip {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  line-height: 1.5;
  padding-left: 2px;
}

/* 悬停效果 */
.avatar-container:hover {
  border-color: #409EFF;
  background-color: rgba(64, 158, 255, 0.05);
}

/* 响应式调整 */
@media (max-width: 480px) {
  .avatar-upload {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .upload-tip {
    width: 100%;
  }
}
</style>